package com.cuit.jifver.jqgridtest.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class MainServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		
		System.out.println(request.getQueryString());
		String result = getJson();
		System.out.println(result);
		
		
		out.write(result);
		out.flush();
		out.close();
	}
	
	
	
	public String getJson()
	{
		// 定义返回的数据类型：json，使用了json-lib
		JSONObject jsonObj = new JSONObject();
		
		// 根据jqGrid对JSON的数据格式要求给jsonObj赋值
		jsonObj.put("page", 1);		// 当前页
		jsonObj.put("total", 1);	// 总页数
		jsonObj.put("records", 4);	// 总记录数
		
		// 定义rows，存放数据
		JSONArray rows = new JSONArray();
		// 放入4条数据
		for(int i=0;i<4;i++)
		{
			// 存放一条记录的对象
			JSONObject cell = new JSONObject();
			cell.put("id", i);
			if(i%2==0)
			{
				cell.put("userName", "polaris");
				cell.put("gender", "女");
			}
			else
			{
				cell.put("userName", "徐新华");
				cell.put("gender", "男");
			}
			cell.put("email", "polaris@gmail.com");
			cell.put("QQ", "772"+i+"1837"+i);
			cell.put("mobilePhone", "132"+i+"1837"+i+"3"+i);
			cell.put("birthday", "198"+i+"-10-"+"1"+i);
			
			// 将该记录放入rows中
			rows.add(cell);
		}
		
		// 将rows放入json对象中
		jsonObj.put("rows", rows);
		return jsonObj.toString();
	}

}
